﻿using System.Drawing;
using System.Globalization;
using System.Text;

namespace TcpJsonService.Core
{
    /// <summary>
    /// 字节和文本转换
    /// </summary>
    public static class ByteConvert
    {
        /// <summary>
        /// 字节流转十六进制字符串
        /// </summary>
        /// <param name="buffer">字节流</param>
        /// <returns>十六进制字符串</returns>
        public static string ToHex(ICollection<byte> buffer)
        {
            return ToHex(buffer, buffer.Count);
        }

        /// <summary>
        /// 字节流转十六进制字符串
        /// </summary>
        /// <param name="buffer">字节流</param>
        /// <param name="size">需要转换的长度</param>
        /// <returns>十六进制字符串</returns>
        public static string ToHex(IEnumerable<byte> buffer,int size)
        {
            StringBuilder builder = new();
            int n = 0;
            foreach (byte b in buffer)
            {
                if (n < size)
                {
                    builder.AppendFormat("{0:x2} ", b);
                }
                else
                {
                    break;
                }
                n += 1;
            }

            return builder.ToString();
        }

        /// <summary>
        /// 十六进制字符串转字节流
        /// </summary>
        /// <param name="value"></param>
        /// <param name="separator">分隔符，默认为" "</param>
        /// <returns>字节流</returns>
        public static byte[] ToBuffer(string value, string separator = " ")
        {
            return value.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries).Select(data => byte.Parse(data, NumberStyles.HexNumber)).ToArray();
        }
    }
}
